const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const onerror = require('koa-onerror');
const serve = require('koa-static');
const path = require('path');
const Router = require('@koa/router');
const setupRouter = require('./router');

const MAX_AGE = 1000 * 60 * 5;

module.exports = (server, options) => {
  const app = new Koa();
  const router = new Router();
  app.proxy = true;
  app.silent = true;
  onerror(app);
  
  // 设置路由
  setupRouter(router);
  
  // 中间件顺序很重要
  app.use(bodyParser());
  app.use(router.routes());
  app.use(router.allowedMethods());
  
  // 静态文件服务
  app.use(serve(path.join(__dirname, '../../public'), { maxage: MAX_AGE }));
  
  // 注册到 Whistle 服务器
  server.on('request', app.callback());
  
  console.log('[NoHost] UI Server 已启动，路由已注册');
  console.log('[NoHost] 插件主页: /plugin.nohost/');
  console.log('[NoHost] API 基础路径: /plugin.nohost/cgi-bin/api/');
};
